<template>
  <a-modal
    title="编辑设备表"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          style="display: none;"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input v-decorator="['id']"/>
        </a-form-item>
        <a-form-item
          label="设备名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input
            placeholder="请输入设备名称"
            v-decorator="['deviceName', {rules: [{required: true, message: '请输入设备名称！'}]}]"/>
        </a-form-item>
        <a-form-item
          label="设备类型"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-select
            :showSearch="true"
            optionFilterProp='children'
            style="width: 100%"
            placeholder="请选择设备类型"
            v-decorator="['productModel', {rules: [{ required: true, message: '请选择设备类型！' }]}]">
            <a-select-option v-for="(item,index) in deviceList" :key="index" :value="item.code">{{
              item.value
            }}
            </a-select-option>
          </a-select>
        </a-form-item>



        <a-form-item
          style="display: none;"
          label="设备厂商"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <!--<a-select style="width: 100%" placeholder="请选择所属站点" v-decorator="['stationId', {rules: [{ required: true, message: '请选择所属站点！' }]}]" >
            <a-select-option v-for="(item,index) in groupCodeList" :key="index" :value="item.code" >{{ item.name }}</a-select-option>
          </a-select>-->
          <a-input v-decorator="['stationId']"/>
        </a-form-item>
        <a-form-item
          label="设备厂商"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input
            placeholder="请输入设备厂商"
            v-decorator="['productVendor', {rules: [{required: true, message: '请输入设备厂商！'}]}]"/>
        </a-form-item>
        <a-form-item
          label="所属行业"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-select
            style="width: 100%"
            placeholder="请选择所属行业"
            v-decorator="['industryId', {rules: [{ required: true, message: '请选择所属设备！' }]}]">
            <a-select-option v-for="(item,index) in industryTypeList" :key="index" :value="item.id">{{
              item.industryType
            }}
            </a-select-option>
          </a-select>
        </a-form-item>



        <a-form-item
          label="投产日期"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-date-picker placeholder="请选择生产日期" @change="onChange" style="width: 100%" v-decorator="['createdAt']"/>
        </a-form-item>

        <a-form-item
          label="设备正面预览图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left"
        >
          <a-upload
            name="fileName"
            :customRequest="customRequest"
            @preview="handlePreview"
            list-type="picture-card"
            :show-upload-list="false"
            :file-list="fileList"
            @change="change"
          >
            <img v-if="fileName" :src="fileName | imgPath" alt="avatar" style="width: 100px;height: 100px;"/>
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'"/>
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>

        </a-form-item>
        <a-form-item
          label="设备背面预览图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left;margin-bottom: 0px;"
        >
          <a-upload
            name="backFileName"
            :customRequest="customRequestback"
            @preview="handlePreview"
            list-type="picture-card"
            :show-upload-list="false"
            :file-list="backFileList"
            @change="changeback"
          >
            <img v-if="backFileName" :src="backFileName | imgPath" alt="avatar" style="width: 100px;height: 100px;" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>

        </a-form-item>
        <a-form-item
          label="设备铭牌预览图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left;margin-bottom: 0px;"
        >
          <a-upload
            name="nameplateFileName"
            :customRequest="customRequestnameplate"
            @preview="handlePreview"
            list-type="picture-card"
            :show-upload-list="false"
            :file-list="nameplateFileList"
            @change="changenameplate"
          >
            <img v-if="nameplateFileName" :src="nameplateFileName | imgPath" alt="avatar" style="width: 100px;height: 100px;" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>

        </a-form-item>


      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { edit } from '@/api/modular/main/bizdevice/bizDeviceManage'
import { industryTypeList } from '@/api/modular/main/bizindustryinvolved/bizIndustryInvolvedManage'
import moment from 'moment'
import { getUploadFileName } from '@/api/modular/system/fileManage'
import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'

export default {
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      visible: false,
      confirmLoading: false,
      groupCodeList: {},
      form: this.$form.createForm(this),
      birthdayString: [],
      industryTypeList: [],
      deviceList: [],
      fileName: '',
      backFileName: '',
      nameplateFileName: '',
      previewVisible: false,
      previewImage: '',
      fileList: [],
      backFileList: [],
      nameplateFileList: [],
      loading: false
    }
  },
  created () {
    this.getIndustryTypeList()
    this.getDeviceList()
  },
  methods: {
    edit (record) {
      this.visible = true
      this.fileName = record.fileName
      this.backFileName = record.backFileName
      this.nameplateFileName = record.nameplateFileName
      setTimeout(() => {
        this.form.setFieldsValue({
          id: record.id,
          productModel: record.productModel,
          productVendor: record.productVendor,
          industryId: record.industryId,
          stationId: record.stationId,
          deviceName: record.deviceName
        })
      }, 100)
      // 时间单独处理
      if (record.createdAt != null) {
        this.form.getFieldDecorator('createdAt', { initialValue: moment(record.createdAt, 'YYYY-MM-DD') })
      }
      this.createdAt = moment(record.createdAt).format('YYYY-MM-DD')
    },
    getDeviceList () {
      sysDictTypeDropDown({ code: 'device_type' }).then((res) => {
        if (res.success) {
          this.deviceList = res.data
        }
      })
    },
    getIndustryTypeList () {
      industryTypeList().then(res => {
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.industryTypeList = res.data
      })
    },
    handleSubmit () {
      const { form: { validateFields } } = this
      this.confirmLoading = true

      validateFields((errors, values) => {
        if (!errors) {
          values.fileName = this.fileName
          values.backFileName = this.backFileName
          values.nameplateFileName = this.nameplateFileName
          edit(values).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('编辑成功')
              this.handleCancel()
              this.$emit('ok', values)
            } else {
              this.$message.info('编辑失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    onChange (date, dateString) {
      if (date == null) {
        this.birthdayString = []
      } else {
        this.birthdayString = moment(date).format('YYYY-MM-DD')
      }
    },
    handleCancel () {
      this.form.resetFields()
      this.visible = false
      this.fileName = ''
      this.fileList = []
      this.backFileName = ''
      this.backFileList = []
      this.nameplateFileName = ''
      this.nameplateFileList = []

    },
    getBase64 (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    },
    previewCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    change ({ fileList }) {
      this.fileList = fileList
    },
    /**
     * 上传文件
     */
    customRequest (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      getUploadFileName(formData).then((res) => {
        if (res.success) {
          this.$message.success('上传成功')
          this.fileName = res.data
          data.onSuccess(res, data.file)
        } else {
          this.$message.error('上传失败：' + res.message)
        }
      })
    },
          /**
       * 上传文件 customRequestback
       */
       customRequestback (data) {
        const formData = new FormData()
        formData.append('file', data.file)
            getUploadFileName(formData).then((res) => {
              if (res.success) {
                this.$message.success('上传成功')
                this.backFileName = res.data
                data.onSuccess(res, data.file)
              } else {
                this.$message.error('上传失败：' + res.message)
              }
            })
      },
      changeback ({ fileList }) {
        this.backFileList = fileList
      },
      // 上传文件

      customRequestnameplate (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        getUploadFileName(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.nameplateFileName = res.data
            data.onSuccess(res, data.file)
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      changenameplate ({ fileList }) {
        this.nameplateFileList = fileList
      },
  }
}
</script>
